<?php

namespace app\controller;

use ali\Sms;
use app\BaseController;
use app\model\Area;
use app\model\CgasStation;
use app\model\Order;
use app\model\PlateformCode;
use app\model\ScoreUpload;
use app\model\User;
use app\model\UserScoreRecharge;
use app\model\UserValidateBalance;
use cgas\CGas;
use think\response\Json;

class Index extends BaseController
{
    public function index()
    {
//        dd(setPassword("123456"));
        return redirect("/html");
//        return '<style>*{ padding: 0; margin: 0; }</style><iframe src="https://www.thinkphp.cn/welcome?version=' . \think\facade\App::version() . '" width="100%" height="100%" frameborder="0" scrolling="auto"></iframe>';
    }

    public function hello($name = 'ThinkPHP8')
    {
//        openssl_decrypt();
        return 'hello,' . $name;
    }

    public function test()
    {
        return json($this->app->make(CGas::class)->lst());
//        dd($this->app->make(CGas::class)->query('18001989683378921717'));
//        $data = $this->app->make(CGas::class)->pay('16005042458059',"18328378446","12345678990");
//        return json($data);
//        echo (strtotime("+7 day"));
//        dd(htmlspecialchars(str_replace(["\r\n","\n","\t"],"",'<p class="tips">使用规则</p><ol class="recharge-its"><li>仅限四川省中国石油自营加油站可使用;</li><li>仅限使用【中油好客e站】加油消费时抵扣;</li><li>不叠加、不找零、不拆分，不兑现金，过期失效;</li><li>自领取之日起30天有效。</li></ol><p class="tips">使用流程</p><p>
//<img src="https://panda.verjs.cn/upload/editor/20250101/39964ffb0d4e402d39a898994dbf2687.png" width="100%"/></p>')));
//        //防止内存溢出
//        @ini_set("memory_limit", -1);
//        $tree = $this->app->make(Area::class)->areaTree();
//        return json($tree);
//        $this->app->make(Sms::class)
//        $data = Sms::sendSms("18328378446",['code'=>123456],'SMS_474460088',"
//成都富海天下科技");
//        return json($data);
//        return json($this->app->make(PlateformCode::class)->codeDetail());
//        $qrcode = $this->app->make(Qrcode::class);
//        $code = $qrcode->createQrcode("https://www.baidu.com",120);
//        $label = $qrcode->createLabel("123456");
//        return $qrcode->files($code,null,$label);
    }

    public function getD()
    {
//        dd($this->app->make(CGas::class)->outQuery("250616024941784902"));
//        return \json($this->app->make(CGas::class)->getAes("394b488142a65dcf989864ce507a099bc06b776a5fc94629157170e2dfcc2d37891d3963de6eaf77a8f9b60a0fbaf37ef36d5c4692f6148af9bf04dafab250c61474d165255a37517322660e492a9a3f4f05db16f9b079ece01dd1b91fa94db3"));
    }

    public function sendCode(): Json
    {
//        $data = Sms::sendSms($this->request->param("mobile"), ['code' => 123456], 'SMS_474460088');
//        return json($data);
        dd(sendSms("191585", $this->request->param("mobile"), ["code" => "123456"]));
    }

    public function ali()
    {
        $sms = $this->app->make(\ali\Sms::class)->sendSms($this->request->param("mobile"), ['code' => 123456], "SMS_474460088");
        return \json($sms);
    }

    public function gas()
    {
        $model = $this->app->make(CgasStation::class);
//        dd($gas);
//https://apis.map.qq.com/ws/geocoder/v1/?address=
//        $client = new \GuzzleHttp\Client([
//            "verify"=>false,
//            "base_uri"=>"https://apis.map.qq.com"
//        ]);
        $gas = $model->whereNull("amap_location")->limit(30)->select()->toArray();
        if (!empty($gas)) {
//            dd($gas);
            $flag = true;
            foreach ($gas as &$value) {
                $url = "https://restapi.amap.com/v3/geocode/geo?address=" . $value['address'] . $value['name'] . "&key=2ee9917dd582af48316293deb1deecca";
                $data = json_decode(file_get_contents($url), true);
                if ($data['status'] == 1) {
                    $value['amap_location'] = ($data['geocodes'][0]['location']);
                } else {
                    dd($url);
                }
            }
            $model->saveAll($gas);
//            return json($gas);
            sleep(10);
            if ($flag)
                echo "<script>window.location.reload()</script>";
            else return json($gas);
        }
    }

    public function que()
    {
        return \json($this->app->make(CGas::class)->query($this->request->param("order")));
    }

    public function inseertOrder(): Json
    {
        $model = $this->app->make(CGas::class)->pay(
            $this->request->param('code'),
            $this->request->param('mobile'),
            $this->request->param('order')
        );
        return json($model);
    }

    public function refund()
    {
        return json($this->app->make(CGas::class)->cancel($this->request->param("order")));
    }

    public function score_up()
    {
        $model = $this->app->make(ScoreUpload::class);
        $data = $model->where('state', 1)->limit(50)->select()->toArray();
        if (empty($data)) return json([
            'code' => 200,
            'msg' => '没有数据'
        ]);
//        $model = app(User::class);
        $item = array_map(function ($value) use ($model) {
            return json_decode($value['content'], true);
        }, $data);
        $this->app->make(UserScoreRecharge::class)->changeAll($item);
        $model->whereIn('id', array_column($data, 'id'))->save(['state' => 2]);
        return redirect("?t=" . microtime());
    }

    public function reloadRefund()
    {
        $order = $this->app->make(Order::class)->where('state', 3)->select()->toArray();
        $its = [];
        if (!empty($order)) {
            foreach ($order as $value) {
                if (!empty($value['cancel_time'])) {
                    //计算两个时间的间隔天数
                    $start = new \DateTime($value['create_time']);
                    $end = new \DateTime($value['cancel_time']);
                    $day = $end->diff($start)->days;
                    if ($day < 59) {
                        $its[] = $value['id'];
                    }
                }
            }
        }
        if (!empty($its)) {
            $this->app->make(Order::class)->whereIn('id', $its)->save(['state' => 5]);
        }
        return \json($its);
    }

    public function validateTime(): Json
    {
        $tim = strtotime(date("Y-m-01 23:59:59"));
        //积分有效期为6个月
        $last_time = date("Y-m-t H:i:s", strtotime("+1 year", $tim));
        $user = $this->app->make(User::class)->where('id', '<>', 15)->where('balance', '>', 0)->column("id uid,balance");
        $item = array_map(function ($item) use ($last_time) {
            $item['last_time'] = $last_time;
            return $item;
        }, $user);
        $this->app->make(UserValidateBalance::class)->saveAll($item);
        return json($item);
    }

    public function lasrTimeScore(): Json
    {
        $data = $this->app->make(UserValidateBalance::class)->decAllBalance();
        return json($data);
    }

    public function q()
    {
        $req = $this->request->param();
        $data = $this->app->make(CGas::class)->query_order([
            "out_trade_no" => $req['order'],
            "request_code" => $req['code'],
            "user_code" => $req['mobile']
        ]);
        return json($data);
    }

    public function queryCode(): Json
    {
        $or = $this->app->make(Order::class);
        $order = $or->with(['attr'])->whereRaw("code is null or code = ''")->where('state', 1)->select()->toArray();
        $cgas = new CGas();
        $items = [];
        if (!empty($order)) {
            foreach ($order as $value) {
                $its = json_decode($value['account'], true);
                $its = array_column($its, 'value', "text");
                $code = explode("-", $value['attr']['code']);
                $que = $cgas->query_order([
                    "out_trade_no" => $value['order_sn'],
                    "request_code" => end($code),
                    "user_code" => $its['mobile']
                ]);
                if ($que['code'] == 0) {
                    $items[] = [
                        "id" => $value['id'],
                        "code" => $que['data']['ticket_list'][0]['ticket_num'],
                        "cont" => json_encode($que['data']['ticket_list'], 320)
                    ];
                }
            }
        }
        if (!empty($or)) {
            $or->saveAll($items);
        }
        return json($items);
    }
}
